package org.biubiu0002.baiblog.core.async.listener;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.biubiu0002.baiblog.core.async.event.FollowEvent;
import org.biubiu0002.baiblog.core.config.RabbitMqConfig;
import org.biubiu0002.baiblog.core.service.FeedService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author: biubiu0002
 * @Date: 2022/8/4 17:54
 **/
@Component
@Slf4j
@RabbitListener(queues = RabbitMqConfig.FOLLOW_QUEUE)
public class FollowListener {

    @Resource
    private FeedService feedService;

    @RabbitHandler
    public void onMessage(String msg, Channel channel, Message message) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            Preconditions.checkArgument(StringUtils.isNotBlank(msg));
            log.info("[关注/取关消息]:{}",msg);
            FollowEvent followEvent = JSON.parseObject(msg, FollowEvent.class);
            String uid = followEvent.getUid();
            String followUid = followEvent.getFollowUid();
            Integer isFollow = followEvent.getIsFollow();

            feedService.handleFollow(uid,followUid,isFollow);

            channel.basicAck(deliveryTag,false);

        }catch (Exception e){
            if (Boolean.TRUE.equals(message.getMessageProperties().isRedelivered())) {
                log.error("[消费拒绝]:{}",message,e);
                channel.basicReject(deliveryTag,false);
            }else{
                log.warn("[消费重试]:{}",message,e);
                channel.basicNack(deliveryTag,false,true);
            }

        }
    }
}
